package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.ChuanShuJinRongUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 四川川蜀锦蓉
 */
@Service
public class ChuanShuJinRongPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("md5Phone", memberSourceInfo.getMobileMd5());

        log.info("【川蜀锦蓉】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【川蜀锦蓉】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "" );
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "100")) {

            pushApiResult.setMessage(msg);
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap= new HashMap<>();
        bizMap.put("username", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("loan", ChuanShuJinRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("gjj", ChuanShuJinRongUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("house", ChuanShuJinRongUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", ChuanShuJinRongUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", ChuanShuJinRongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("xyk", ChuanShuJinRongUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("shebao", ChuanShuJinRongUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("promotion_prefix", "推广10");
        bizMap.put("sex", memberSourceInfo.getSex()==1?0:1);
        bizMap.put("age", String.valueOf(memberSourceInfo.getAge()));
        bizMap.put("job", ChuanShuJinRongUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("degree", ChuanShuJinRongUtil.getXueLi(memberSourceInfo.getXueli()));
        bizMap.put("company_id", Integer.valueOf(pushApiKeyParam.getApiCode()));


        log.info("【川蜀锦蓉】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【川蜀锦蓉】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "" );
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "100")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }



    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encryptData(String plainText,String keyHex,String ivHex) throws Exception {

        // 将16进制字符串转换为字节数组
        byte[] keyBytes = hexStringToByteArray(keyHex);
        byte[] ivBytes = hexStringToByteArray(ivHex);

        // 扩展密钥到24字节
        byte[] key24Bytes = new byte[24];
        System.arraycopy(keyBytes, 0, key24Bytes, 0, keyBytes.length);  // 复制16字节密钥
        // 填充剩余8字节
        for (int i = keyBytes.length; i < key24Bytes.length; i++) {
            key24Bytes[i] = 0x00;  // 使用0填充剩余字节
        }

        // 创建DESede密钥
        SecretKey key = new javax.crypto.spec.SecretKeySpec(key24Bytes, "DESede");

        // 创建IvParameterSpec
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        // 创建Cipher实例，使用DESede CBC模式，PKCS5Padding填充
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);


        // 加密
        byte[] encrypted = cipher.doFinal(plainText.getBytes());

        // 将加密后的数据转换为Base64字符串
        String encryptedBase64 = Base64.getEncoder().encodeToString(encrypted);

        return encryptedBase64;
    }

    // 16进制字符串转换为字节数组
    public static byte[] hexStringToByteArray(String hex) {
        int length = hex.length();
        byte[] data = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }
}
